'use strict';

import gulp from 'gulp';
import uglify from 'gulp-uglify';
import babel from 'gulp-babel';
import concat from 'gulp-concat';
import jsEncrypt from 'gulp-js-encrypt';
import rename from 'gulp-rename';
import less from 'gulp-less';
import LessAutoprefix from 'less-plugin-autoprefix';
import LessPluginCleanCSS from 'less-plugin-clean-css';
import sourcemaps from 'gulp-sourcemaps';
import packageData from "./package.json" assert { type: 'json' };

const cleanCSS = new LessPluginCleanCSS({ advanced: true });
const autoprefix = new LessAutoprefix({ browsers: packageData.browserslist });


const csspath='./resource/less/**/[^_]*.less';
function cssTask() {
    return gulp.src(csspath)
        .pipe(sourcemaps.init())
        .pipe(less({ plugins: [autoprefix, cleanCSS] }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./static/css'));
}


const jspath='./resource/js/**/[^_]*.js';
function frontTask() {
    return gulp.src(jspath)
        .pipe(sourcemaps.init())
        //.pipe(jsImport({hideConsole: true}))
        .pipe(babel({
            presets: ['@babel/preset-env']
        }))
        //.pipe(concat('app.js'))
        //.pipe(rename({ basename: 'init' }))
        //.pipe(gulp.dest('./static/js/'))  //输出未压缩文件
        .pipe(uglify())
        .pipe(jsEncrypt())
        .pipe(rename(function(path){
            //选择性重命名文件
            if(!path.dirname.match(/\bapp\b/)){
                path.extname = '.min.js';
            }
        }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./static/js/'));
}


function watchAll() {
    
    console.log('Starting watch all files...');
    gulp.watch('./resource/less/**/*.scss',cssTask, (event)=> {
        console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
    gulp.watch('./resource/js/**/*.js',frontTask,(event)=> {
        console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
}

const build = gulp.parallel(cssTask,frontTask);

gulp.task('default', gulp.series(build,watchAll));
gulp.task('build', build);
gulp.task('watch', watchAll);

